import React, { useState } from 'react';
import './UserSettings.css';

const UserSettings = ({ user, onUpdate }) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');
    const formData = new FormData(e.target);
    const values = Object.fromEntries(formData.entries());

    // 只发送已填写的字段
    const updates = {};
    if (values.currentPassword) updates.currentPassword = values.currentPassword;
    if (values.newPassword) updates.newPassword = values.newPassword;
    if (values.amapKey) updates.amapKey = values.amapKey;
    if (values.securityJsCode) updates.securityJsCode = values.securityJsCode;
    updates.username = user.username;

    try {
      setLoading(true);
      const response = await fetch('/api/user/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updates),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '更新失败');
      }

      setSuccess('更新成功');
      onUpdate(data);
      e.target.reset();
    } catch (error) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="settings-container">
      <h2>用户设置</h2>
      {error && <div className="error-message">{error}</div>}
      {success && <div className="success-message">{success}</div>}
      <form onSubmit={handleSubmit} className="settings-form">
        <div className="form-section">
          <h3>修改密码</h3>
          <div className="form-group">
            <label htmlFor="currentPassword">当前密码</label>
            <input
              type="password"
              id="currentPassword"
              name="currentPassword"
              placeholder="输入当前密码"
            />
          </div>
          <div className="form-group">
            <label htmlFor="newPassword">新密码</label>
            <input
              type="password"
              id="newPassword"
              name="newPassword"
              placeholder="输入新密码"
            />
          </div>
        </div>

        <div className="form-section">
          <h3>高德地图配置</h3>
          <div className="form-group">
            <label htmlFor="amapKey">高德地图Key</label>
            <input
              type="text"
              id="amapKey"
              name="amapKey"
              placeholder="输入新的高德地图Key"
            />
          </div>
          <div className="form-group">
            <label htmlFor="securityJsCode">安全密钥</label>
            <input
              type="text"
              id="securityJsCode"
              name="securityJsCode"
              placeholder="输入新的安全密钥"
            />
          </div>
          <div className="form-help">
            <p>在高德开放平台获取 Key 和安全密钥：</p>
            <ol>
              <li>访问 <a href="https://console.amap.com/dev/key/app" target="_blank" rel="noopener noreferrer">高德开放平台</a></li>
              <li>创建新应用或选择现有应用</li>
              <li>添加 Key，服务平台选择 "Web端(JS API)"</li>
              <li>在 Key 详情中获取安全密钥</li>
            </ol>
          </div>
        </div>

        <button 
          type="submit" 
          className="submit-button" 
          disabled={loading}
        >
          {loading ? '更新中...' : '更新设置'}
        </button>
      </form>
    </div>
  );
};

export default UserSettings; 